﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

namespace Kokomo
{
	public static class StreamExtensions
	{
		public static TStruct[] ReadStructArray<TStruct>(this Stream stream, int arrayLength)
			where TStruct : struct
		{
			TStruct[] array = new TStruct[arrayLength];
			for (int i = 0; i < array.Length; i++)
			{
				TStruct s = stream.ReadStruct<TStruct>();
				array[i] = s;
			}
			return array;
		}
		public static TStruct ReadStruct<TStruct>(this Stream stream)
			where TStruct : struct
		{
			ArgumentValidation.CheckNullArgument("stream", stream);

			int size = Marshal.SizeOf(typeof(TStruct));
			byte[] buffer = new byte[size];
			stream.Read(buffer, 0, size);

			TStruct value = buffer.ToStruct<TStruct>();

			return value;
		}
		public static void WriteStruct<TStruct>(this Stream stream, TStruct record)
			where TStruct : struct
		{
			ArgumentValidation.CheckNullArgument("stream", stream);

			byte[] buffer = record.ToMarshaledByteArray();
			stream.Write(buffer, 0, buffer.Length);
		}
		public static string ReadAsciiZ(this Stream stream)
		{
			ArgumentValidation.CheckNullArgument("stream", stream);

			StringBuilder builder = new StringBuilder();
			BinaryReader reader = new BinaryReader(stream, Encoding.ASCII);
			char c = reader.ReadChar();
			while (c != 0)
			{
				builder.Append(c);
				c = reader.ReadChar();
			}

			return builder.ToString();
		}
	}
}
